package com.ylr.base.framework.interceptor;

import com.ylr.base.common.constant.Constant;
import com.ylr.base.common.po.user.UserPo;
import com.ylr.base.common.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2023-05-04 21:45:17
 * className: UserInterceptor 用户拦截器
 * version: 1.0
 * description:
 */
public class UserInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(UserInterceptor.class);

    /**
     * 1、前置拦截
     * @param request  http请求对象
     * @param response http请求结果对象
     * @param handler  目标接口对象
     * @return 校验结果[true-通过 false-拒绝]
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            log.warn("UserInterceptor 非请求接口操作，直接放行。requestUri={}", request.getRequestURI());
            return true;
        }
        String authResult = request.getHeader(Constant.AUTH_RESULT);
        String userPo = request.getHeader(UserPo.class.getSimpleName());

        log.debug("上游服务传递参数。authResult={} userPo={}", authResult, userPo);
        if (Constant.AUTH_PASS.equals(authResult)) {
            // 已经认证过
            if (StringUtils.isEmpty(userPo)) {
                // 设置请求用户
                UserUtils.setUser(userPo);
            }
        }
        return true;
    }

    /**
     * 3、最终拦截
     * @param request  http请求对象
     * @param response http请求结果对象
     * @param handler  目标接口对象
     * @param ex       异常对象
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 清理请求用户
        UserUtils.deleteUser();
    }

}